<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\CategoryModel;
use app\model\MenusModel;
use app\model\RedisModel;
use think\App;
use think\facade\Db;

class Menus extends Base {

    protected $middleware = [Auth::class];
    private $menusModel;

    public $cacheKey="menus:id:";

    private $req;

    private $page;

    private $limit;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 999999;

        $this->menusModel = new MenusModel();

        $this->isLogin();
    }

    /*
     * 获取店铺列表
     * */
    public function getList(){

        $list = $this->menusModel->getList([],$this->page,$this->limit);

        $total = $this->menusModel->getTotal("","");

        return $this->succData($total,$list);

    }


    /*
    * 新增/删除/修改
    * */
    public function add()
    {

        if(!isset($this->req['menus']) || empty($this->req['menus'])){
            return $this->fail("数据不能为空");
        }

        $menus=[];
        foreach ($this->req['menus'] as $key => $value){

            if(!isset($value['menus_name']) || empty($value['menus_name'])){
                return $this->fail("请输入类目名称");
            }

            if(!isset($value['menus_icon']) || empty($value['menus_icon'])){
                return $this->fail("请上传icon");
            }

            if(!isset($value['menus_url']) || empty($value['menus_url'])){
                return $this->fail("请输入跳转链接");
            }
            $menu = [];
            $menu['menus_name'] = $value['menus_name'];
            $menu['menus_icon'] = $value['menus_icon'];
            $menu['menus_url'] = $value['menus_url'];
            $menu['menus_id'] = $key +1;
            $menus[] = $menu;
        }

        Db::startTrans();
        $delRes = $this->menusModel->delAll();
        $addres = $this->menusModel->batchAdd($menus);
        if($delRes && $addres){
            $this->delAllCache();
            Db::commit();
            return $this->succ();
        }else{
            Db::rollback();
            return $this->fail();
        }
    }




    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }
}
